package com.naiterui.ehp.bs.cms.modules.oms.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;
import com.naiterui.ehp.bs.cms.common.utils.MybatisQueryHelp;
import com.naiterui.ehp.bs.cms.common.vo.PageParamsVO;
import com.naiterui.ehp.bs.cms.common.vo.PageVO;
import com.naiterui.ehp.bs.cms.modules.oms.entity.Order;
import com.naiterui.ehp.bs.cms.modules.oms.entity.OrderUser;
import com.naiterui.ehp.bs.cms.modules.oms.feign.ISystemOrderFeginClient;
import com.naiterui.ehp.bs.cms.modules.oms.mapper.OrderItemMapper;
import com.naiterui.ehp.bs.cms.modules.oms.mapper.OrderLogMapper;
import com.naiterui.ehp.bs.cms.modules.oms.mapper.OrderMapper;
import com.naiterui.ehp.bs.cms.modules.oms.mapper.OrderUserMapper;
import com.naiterui.ehp.bs.cms.modules.oms.service.IOrderService;
import com.naiterui.ehp.bs.cms.modules.oms.vo.OrderExcelVO;
import com.naiterui.ehp.bs.cms.modules.oms.vo.OrderItemVO;
import com.naiterui.ehp.bs.cms.modules.oms.vo.OrderLogVO;
import com.naiterui.ehp.bs.cms.modules.oms.vo.OrderRecomVO;
import com.naiterui.ehp.bs.cms.modules.oms.vo.OrderUserVO;
import com.naiterui.ehp.bs.cms.modules.oms.vo.OrderVO;
import com.naiterui.ehp.bs.cms.modules.oms.vo.RefundSelectPayOrder;
import com.naiterui.ehp.bs.cms.modules.oms.vo.StatisticalVO;
import com.naiterui.ehp.bs.cms.modules.recommend.mapper.RecommPrescriptionMapper;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.collection.CollectionUtil;
import lombok.AllArgsConstructor;

@Service
@AllArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    private final OrderItemMapper orderItemMapper;
    private final OrderUserMapper orderUserMapper;
    private final OrderLogMapper orderLogMapper;
    private final OrderMapper orderMapper;
    private final ISystemOrderFeginClient systemOrderFeginClient;
    private final RecommPrescriptionMapper recommPrescriptionMapper;

    @Override
    public PageVO<OrderVO> queryPage(PageParamsVO pageParamsVO, OrderVO orderVO) {
        // 触发订单状态刷新
        // systemOrderFeginClient.refreshPlatformOrderStatus();

        QueryWrapper<OrderVO> entityWrapper = MybatisQueryHelp.getWrapper(pageParamsVO, orderVO, "t");
        Page<OrderVO> page = this.baseMapper.getPage(pageParamsVO.getPage(), entityWrapper);
        List<OrderVO> orderVOS = page.getRecords();
        if (CollectionUtil.isNotEmpty(orderVOS)) {
            List<Long> orderIds = orderVOS.stream().map(e -> e.getId()).collect(Collectors.toList());
            Object[] orderIdArray = orderIds.toArray();
            List<OrderRecomVO> orderRecomVOS = orderMapper.getOrderRecom(orderIdArray);
            Map<Long, Long> orderRecomMap = new HashMap<>();
            orderRecomVOS.forEach(e -> {
                orderRecomMap.put(e.getOrderId(), e.getRecomId());
            });

            orderVOS.forEach(o -> {
                o.setRecomId(null != orderRecomMap.get(o.getId()) ? orderRecomMap.get(o.getId()) : null);
                o.setUserName(StringUtils.isEmpty(o.getUserName()) ? o.getNickName() : o.getUserName());
            });
        }
        return PageVO.toPageVo(orderVOS, page.getTotal(), (int) page.getSize(), (int) page.getCurrent());
    }

    @Override
    public List<StatisticalVO> getStatisticalVO(PageParamsVO pageParamsVO, OrderVO orderVO) {
        QueryWrapper<OrderVO> entityWrapper = MybatisQueryHelp.getWrapper(pageParamsVO, orderVO, "eoi");
        return this.baseMapper.getStatistical(entityWrapper);
    }

    @Override
    public OrderVO getOrderDetails(Long orderId) {
        OrderVO orderVO = this.baseMapper.getById(orderId);

        OrderUserVO orderUserVO = this.orderUserMapper.getOrderIdAndType(orderId, OrderUser.ORDER_TYPE_SHOPPING);
        orderVO.setOrderUser(orderUserVO);

        List<OrderItemVO> orderItemVO = this.orderItemMapper.getByOrderId(orderId);
        orderVO.setOrderItems(orderItemVO);

        // 订单日志
        List<OrderLogVO> logs = this.orderLogMapper.getByOrderId(orderId);
        orderVO.setLogs(logs);
        // 相关处方图片
        String prescriptionPhotoUrl = this.recommPrescriptionMapper.getFirstPrescriptionPhotoUrlByRecomId(orderItemVO.get(0).getRecomId());
        orderVO.setPrescriptionPhotoUrl(ConfigUtil.getString("ehp.domain.img") + prescriptionPhotoUrl);
        return orderVO;
    }

    @Override
    public List<OrderVO> getByPatientId(Long pateintId) {
        return this.baseMapper.getByPatientId(pateintId);
    }

    @Override
    public List<RefundSelectPayOrder> getPayOrder(String orderSn) {
        return this.baseMapper.getPayOrder(orderSn);
    }

    @Override
    public byte[] export(PageParamsVO pageParamsVO, OrderVO orderVO) throws IOException {
        QueryWrapper<OrderVO> entityWrapper = MybatisQueryHelp.getWrapper(pageParamsVO, orderVO, "eoi");
        List<OrderExcelVO> excelList = this.baseMapper.exportOrder(entityWrapper);
        ExportParams exportParams = new ExportParams();
        ByteArrayOutputStream byteArrayOutputStream;
        try (Workbook workbook = ExcelExportUtil.exportExcel(exportParams, OrderExcelVO.class, excelList)) {
            byteArrayOutputStream = new ByteArrayOutputStream();
            workbook.write(byteArrayOutputStream);
        }
        return byteArrayOutputStream.toByteArray();
    }

}
